﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Collections.Generic;

namespace RearLivestock.Beginning.Api.Application.Command.Infancie
{
    public class QueryInfanciesHandler : IRequestHandler<QueryInfanciesCommand, Result<PageResultDto<InfanciesDto>>>
    {
        /// <summary>
        /// 公猪期初仓储
        /// </summary>
        private readonly IBaseRepository<Infancies> infanciesRepository;
        /// <summary>
        /// 猪只信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddInfanciesHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="batchsRepository"></param>
        public QueryInfanciesHandler(IBaseRepository<Infancies> infanciesRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, ILogger<AddInfanciesHandler> logger)
        {
            this.infanciesRepository = infanciesRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<InfanciesDto>>> Handle(QueryInfanciesCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<InfanciesDto>>() { Code = (int)CommonErrorCode.Added, Data = new PageResultDto<InfanciesDto>() };
            var page = new PageResultDto<InfanciesDto>() { TotalCount = 0, PageCount = 0, List = new List<InfanciesDto>() };
            try
            {
                var list = await (from a in await infanciesRepository.GetAll()
                                  join b in await basicInformationRepository.GetAll()
                                  on a.BasicInforId equals b.BasicInforId
                                  join c in await bedroomsRepository.GetAll()
                                  on a.BedroomId equals c.BedroomId
                                  join d in await fieldsRepository.GetAll()
                                 on a.FieldId equals d.FieldId
                                  where a.BasicInforId != 0 || a.BasicInforId == request.BasicInforId && a.IsInfancies==false
                                  select new InfanciesDto()
                                  {
                                      InfancieId = a.InfancieId,
                                      DocumentNumber = a.DocumentNumber,
                                      OpeningDate = a.OpeningDate,
                                      BasicInforId = a.BasicInforId,
                                      BedroomId = a.BedroomId,
                                      FieldId = a.FieldId,
                                      PigNumber = a.PigNumber,
                                      Weight = a.Weight,
                                      IsInfancies = a.IsInfancies,
                                      EarNumber = b.EarNumber,
                                      BedroomName = c.BedroomName,
                                      FieldName = d.FieldName,
                                      CreatedOwner = a.CreatedOwner,
                                      CreatedTime = a.CreatedTime,
                                      UpdateOwner = a.UpdateOwner,
                                      UpdateTime = a.UpdateTime,
                                      ExamineOwner = a.ExamineOwner,
                                      ExamineTime = a.ExamineTime,
                                  }).ToListAsync();
                if (request.BasicInforId != 0)
                {
                    list = list.Where(d => d.BasicInforId == request.BasicInforId).ToList();
                }
                //总条数
                page.TotalCount = list.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.pageSize);
                page.List = list.OrderBy(d => d.InfancieId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = page;
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "公猪期初列表显示成功";
            }
            catch (Exception ex)
            {
                result.Msg = "公猪期初列表显示异常";
                logger.LogError("公猪期初列表显示异常",ex.Message);
            }
            return result;
        }
    }
}
